package com.bearingnavi.android.dialogs;

import android.app.Dialog;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import com.bearingnavi.android.R;
import com.google.android.maps.GeoPoint;

public class NewBearingDialog extends Dialog {
	
	private ConfirmBearingHandler handler;
	private Context context;
//	private boolean isListenerRegister = false;
	private SensorManager sensorManager;
	private SensorEventListener listener;
	private GeoPoint geoPoint;

	public NewBearingDialog(Context context, ConfirmBearingHandler handler, GeoPoint geoPoint) {
		super(context);
		this.handler = handler;
		this.context = context;
		this.geoPoint = geoPoint;
	}
	
	@SuppressWarnings("static-access")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.setContentView(R.layout.new_bearing);
		
		this.setTitle("Draw bearing line");
		
		Button confirm = (Button) findViewById(R.id.confirm);
		final CheckBox sensorBearing = (CheckBox) findViewById(R.id.sensor_bearing);
		final EditText bearing = (EditText) findViewById(R.id.bearing);
		final EditText distance = (EditText) findViewById(R.id.distance);
		
					
		sensorManager = (SensorManager) context.getSystemService(context.SENSOR_SERVICE);
		
		listener = new SensorEventListener() {
			
			public void onSensorChanged(SensorEvent event) {
				
				bearing.setText(event.values[0]+"");
				
			}
			
			public void onAccuracyChanged(Sensor sensor, int accuracy) {	}
		};
		
		sensorBearing.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

				if (isChecked) {
					sensorManager.registerListener(listener, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_FASTEST);	
				} else {
					sensorManager.unregisterListener(listener);
				}
			}
			
		});
		
		confirm.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View view) {
				
				NewBearingDialog.this.dismiss();
				
				GeoPoint fromPoint = geoPoint;
				int wayPoint = 0;
					
				handler.onConfirm(
						new Float(bearing.getText().toString()).intValue(),
						Integer.parseInt(distance.getText().toString()),
						fromPoint, wayPoint);
			}
		});
		
	}
	
	public interface ConfirmBearingHandler {

		void onConfirm(int bearing, int distance, GeoPoint fromPoint, int wayPoint);
	}
	
	@Override
	public void dismiss() {
		
		sensorManager.unregisterListener(listener);
		super.dismiss();
	}

}
